package edu.hcnu.interceptor;

import edu.hcnu.expception.NotAuthorizedException;
import edu.hcnu.po.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Random;

@Component
public class AfterInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(new Random().nextBoolean()){
            return true;
        }

        throw  new NotAuthorizedException("没有权限");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(modelAndView!=null){
            List<User> users = (List<User>) modelAndView.getModel().get("users");
            if(users!=null){
                users.add(new User(300,"我是被拦截器添加的用户",100));
                modelAndView.getModel().put("users",users);
            }
        }
    }
}
